from api import web_api,user_api
from datetime import datetime
from threading import Thread
import sys
from db import db_work
import os
import time


def home():
    print("登录管理界面".center(30, '*'))
    print("01 注册".center(30))
    print("02 登录".center(30))

def home1():
    print("用户功能界面".center(30, '*'))
    print("01 聊天室".center(30))
    print("02 发送文件".center(30))
    print('03 通讯录'.center(30))
    print('04 退出'.center(30))

def home2():
    print('通讯录'.center(30, '*'))
    print('01 添加联系人'.center(30))
    print('02 进入消息列表'.center(30))
    print('_____________输入exit返回上一页面_______________')
'''
聊天室处理接收到的消息
'''
def chat_recv_mes(sock):
    while True:
        data=web_api.recv_mes(sock)
        if data.get('code')=='404':
            print('system>>>',data.get('msg'))
            break
        print(f"({data.get('time')}){data.get('user_name')}:{data.get('msg')}")

def chat(mode,sock,name):
    print('_________欢迎来到聊天室___________')
    t=Thread(target=chat_recv_mes,args=(sock,))
    t.daemon=True
    t.start()
    while True:
        content=input(f'{name}>>>')
        if mode=='talk':
            data=web_api.get_request_dic(mode,user_name=name,msg=content,time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        else:
            data={}
        web_api.send_mes(sock,data)
        if content=='exit':

            return

'''
文件传输函数
'''
def file_(conn):
    while True:
        path=input('请输入文件所在地址：')
        if os.path.isfile(path):
            break
        print('请输入有效地址')
    file_name=os.path.split(path)[-1]
    file_size=os.path.getsize(path)
    data=web_api.get_request_dic(mode='file',file_name=file_name,file_size=file_size)
    web_api.send_mes(conn,data)
    tqdm = web_api.create_tqdm(file_size, file_name)
    db_work.out_save(path,conn,tqdm)
    recv=web_api.recv_mes(conn)
    print(recv.get('msg'))


'''
通讯录函数
'''
def contacts(conn,user_num):
    while True:
        home2()
        choice2 = input()
        if choice2=='exit':
            break
        elif choice2=='1':
            contact_num=input('输入你要添加联系人的信息>>>')
            add_contact(conn,contact_num,user_num)
        elif choice2=='2':
            select_contact_talk(conn,user_num)
        elif choice2=='exit':
            break
        else:
            continue

'''
显示通信录联系人,并返回通信人列表
'''
def show_contact(user_num,conn):
    data = web_api.get_request_dic(mode='contacts', user_num=user_num)
    web_api.send_mes(conn, data)
    recv_data = web_api.recv_mes(conn)
    print(recv_data)
    contact_dic=recv_data.get('msg')
    print('*******通讯录*******')
    count=0
    for i in contact_dic:
        count=count+1
        print(f"{count}:***姓名:{i.get('name')},账号{i.get('user_num')}***")
    print(f'{count+1}:退出')
    return contact_dic

'''
添加联系人
'''
def add_contact(conn,contact_num,user_num):
    time=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    data=web_api.get_request_dic(mode='add_contact', user_num=user_num,contact_num=contact_num,time=time)
    web_api.send_mes(conn, data)
    recv_data=web_api.recv_mes(conn)
    print(f"system>>>{recv_data.get('msg')}")

'''
选择与哪位通讯录联系人对话
'''
def select_contact_talk(conn,user_num):
    while True:
        list_contact = show_contact(user_num, conn)
        try:
            count=int(input('请选择你要和那位联系人进行通信>>>'))
        except ValueError:
            print('请输入合适的值>>>')
            continue
        else:
            if count>0 and count<=len(list_contact):
                contact_talk(conn,user_num,list_contact[count-1].get('user_num'))
            elif count==len(list_contact)+1:
                break
            else:
                print('请输入合适的值>>>')


'''
与contact_num的聊天窗口
'''
def contact_talk(conn,user_num,contact_num):
    data = web_api.get_request_dic(mode='private_message', user1=user_num, user2=contact_num, msg='',time='')
    web_api.send_mes(conn, data)
    user_name=db_work.get_username(user_num)
    history = web_api.recv_mes(conn).get('msg')
    for i in history:
        name1=db_work.get_username(i.get("发信人"))
        name2 = db_work.get_username(i.get("收信人"))
        print(f'{name1}--->{name2}>>>{i.get("content")}({i.get("time")})')
    contact_name=db_work.get_username(contact_num)
    print(f'****{user_name}和{contact_name}的聊天窗口(输入exit可退出该窗口)*****')
    Thread(target=recv_contact,args=(conn,user_num,contact_num)).start()
    while True:
        bool_=send_contact(conn,user_num,contact_num)
        if bool_:
            continue
        else:
            time.sleep(0.5)
            break

'''
向contact_num发送消息
'''
def send_contact(conn,user_num,contact_num):
    name=db_work.get_username(user_num)
    contact_name=db_work.get_username(contact_num)
    msg=input(f'{name}------>{contact_name}')
    time=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    data=web_api.get_request_dic(mode='private_message', user1=user_num,user2=contact_num,msg=msg,time=time)
    web_api.send_mes(conn, data)
    if msg=='exit':
        return False
    else:
        return True



'''
接收contact_num消息
'''
def recv_contact(conn,user_num,contact_num1):
    while True:
        name=db_work.get_username(user_num)
        recv_data=web_api.recv_mes(conn)
        contact_dic=recv_data.get('msg')
        if contact_dic.get('content') == 'exit' :
            break
        else:
            contact_num=contact_dic.get('user_num')
            contact_name=db_work.get_username(contact_num)
            print('\n')
            if contact_num1==contact_num:
                print(f'{contact_name}({contact_num})--->{contact_dic.get("content")}({recv_data.get("time")})')
                print(f"{name}------>{contact_name}",end='')

if __name__ == '__main__':
    sock = web_api.client_create()
    while True:
        home()
        choice=input('请选择你要进行的操作>>>')
        if choice == '1':
            user_name=input('请输入用户名>>>')
            user_num=input('请输入账号>>>')
            user_password=input('请输入密码>>>')
            data=web_api.get_request_dic('register',user_name=user_name,user_num=user_num,user_password=user_password,time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            web_api.send_mes(sock,data)
            dic=web_api.recv_mes(sock)
            print(dic.get('msg'))
        elif choice == '2':
            user_num=input('请输入账号>>>')
            user_password=input('请输入密码>>>')
            data=web_api.get_request_dic('login',user_num=user_num,user_password=user_password,time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            web_api.send_mes(sock,data)
            dic=web_api.recv_mes(sock)
            print(dic.get('msg'))
            if dic.get('code')=='200':
                while True:
                    name = db_work.get_username(user_num)
                    home1()
                    choice=input(f'{name}>>>')
                    if choice == '1':
                        data=web_api.get_request_dic(mode='talk',user_name=name,msg='用户进入聊天室',time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
                        web_api.send_mes(sock,data)
                        chat('talk',sock,name)
                    elif choice == '2':
                        file_(sock)
                    elif choice == '3':
                        contacts(sock,user_num)
                    elif choice == '4':
                        data = web_api.get_request_dic(mode='exit', user_name=name,time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
                        web_api.send_mes(sock, data)
                        break
                    else:
                        print('system>>>请输入正确指令')
                        continue
            else:
                print('system>>>',dic.get('msg'))
                continue

        else:
            sys.stdout.flush()
            os.system('cls')
